# -*- coding: utf-8 -*-

"""
@Datetime: 2019/3/13
@Author: Zhang Yafei
"""
import os
import os.path as op

from flask_admin import Admin, form
from flask_admin.contrib.sqla import ModelView
from jinja2 import Markup
from sqlalchemy.event import listens_for

from application import app, db
from common.libs.UrlManager import UrlManager
from common.models.models import User, AppErrorLog, AppAccessLog

file_path = op.join(op.dirname(__file__), 'static')  # 文件上传路径

admin = Admin(app, name='beautifulData', template_mode='bootstrap3')


class BaseModelview(ModelView):
    def getinfo(self):
        return "this is another model"


class UserAdmin(BaseModelview):
    column_labels = {
        'nickname': '昵称',
        'mobile': '手机号',
        'email': '邮件',
        'avatar': '头像',
        'sex_desc': '性别',
    }

    column_exclude_list = ['login_pwd', 'login_name', 'login_salt', 'status', 'sex']
    column_filters = ['sex']

    column_searchable_list = ['login_name', 'email']
    column_editable_list = ['nickname', 'email']
    form_excluded_columns = ['login_name', 'email']

    # 设置缩略图的
    def _list_thumbnail(view, context, model, name):
        if not model.avatar:
            return ''

        return Markup('<img src="%s">' % UrlManager.buildStaticUrl(path=model.avatar))

    # 格式化列表的图像显示
    column_formatters = {
        'avatar': _list_thumbnail
    }
    # 扩展列表显示的头像为60*60像素
    form_extra_fields = {
        'avatar': form.ImageUploadField('avatar',
                                        base_path=file_path,
                                        relative_path='images/photo/',
                                        thumbnail_size=(60, 60, True))
    }


##监听删除图片的
@listens_for(User, 'after_delete')
def del_image(mapper, connection, target):
    if target.avatar:
        # Delete image
        try:
            os.remove(op.join(file_path, target.avatar))
        except OSError:
            pass

        # Delete thumbnail
        try:
            os.remove(op.join(file_path,
                              form.thumbgen_filename(target.avatar)))
        except OSError:
            pass


admin.add_view(UserAdmin(User, db.session, name='用户管理'))
admin.add_view(BaseModelview(AppAccessLog, db.session, name='用户访问日志'))
admin.add_view(BaseModelview(AppErrorLog, db.session, name='用户错误日志'))
